package com.eastedu.superise.handler.basic;

import com.eastedu.client.file.model.FileInfoResponse;
import com.eastedu.converter.BasicResourceFileConverter;
import com.eastedu.manager.BasicResourceManager;
import com.eastedu.manager.FileManager;
import com.eastedu.model.basic.ResourceFile;
import com.eastedu.repository.basic.mapper.BasicResourceFileMapper;
import com.eastedu.repository.basic.mapper.BasicResourceMapper;
import com.eastedu.repository.basic.po.BasicResourceFilePO;
import com.eastedu.superise.handler.AbstractHistoricalDataHandler;
import com.eastedu.util.UrlParser;
import com.eastedu.utils.JsonUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 处理zip格式微课
 * @author zhangzhishuai
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ZipMicroCourseV2HistoricalDataHandler extends AbstractHistoricalDataHandler<BasicResourceFilePO> {

    private final FileManager fileManager;
    private final BasicResourceFileMapper basicResourceFileMapper;
    private final BasicResourceFileConverter basicResourceFileConverter;
    private final BasicResourceManager basicResourceManager;
    private final BasicResourceMapper basicResourceMapper;


    @Override
    protected String getSql() {
        return "SELECT f.* FROM t_basic_resource br INNER JOIN t_basic_resource_file f ON br.id = f.basic_resource_id WHERE br.category = 9 AND extension = 'zip' ";
    }

    @Override
    public void callback(BasicResourceFilePO po) throws SQLException {

        Optional<ResourceFile> fileOptional = getResourceFile(po);
        if (!fileOptional.isPresent()) {
            log.warn("无效的视频资源");
            return;
        }

        String previewUrl = fileOptional.get().getPreviewUrl();
        Optional<String> optional = UrlParser.extractFileNameFromUrl(previewUrl);
        if (!optional.isPresent()) {
            log.warn("url解析错误，跳过，ID：{}", po.getId());
            return;
        }
        FileInfoResponse fileInfoResponse = fileManager.getFileInfoByMd5(optional.get());
        if (Objects.isNull(fileInfoResponse)) {
            log.warn("文件信息错误，跳过，ID：{}", po.getId());
            return;
        }
        this.basicResourceFileConverter.update(fileInfoResponse, po);
        this.basicResourceFileMapper.updateById(po);

        basicResourceManager.updateFileJsonByResourceId(po.getBasicResourceId());

    }

    private Optional<ResourceFile> getResourceFile(BasicResourceFilePO po) {
        String filesJson = this.basicResourceMapper.selectById(po.getBasicResourceId()).getFilesJson();
        List<ResourceFile> resourceFiles = JsonUtil.parseList(filesJson, ResourceFile.class);
        return resourceFiles.stream().filter(o -> o.getPreviewUrl().endsWith("mp4")).findAny();
    }

}
